﻿Array.prototype.each = function (action) {
    for (var i = 0; i < this.length; i++)
        action(this[i]);
};
//数组中是否包含制定的项
Array.prototype.contains = function (item) {
    for (var i = 0; i < this.length; i++)
        if (this[i] == item) return true;
    return false;
}
Array.prototype.indexOf = function (item) {
    for (var i = 0; i < this.length; i++)
        if (this[i] == item) return i;
    return -1;
}
//此方法有两个功能，
//1.不传入limit,则只获取文本的字节长度
//2.如果传入limit，即限定长度，则检查字节长度是否超出limit的范围。如果长度超出limit则返回true,否则返回false。
String.prototype.getByteLength = function (limit) {
    var byteLength = 0;
    for (var i = 0; i < this.length; i++) {
        if (this.charCodeAt(i) > 255) byteLength += 2;
        else byteLength++;
        if (limit && typeof (limit) == "number" && byteLength > limit) return true;
    }
    if (limit && typeof (limit) == "number") return false;
    return byteLength;
};
String.prototype.toNumber = function () {
    var v = parseFloat((this + "").replace(/^\s+|\s+$/g, ""));
    if (isNaN(v)) return 0;
    else return v;
}
Number.prototype.round = function (precision) {
    if (this == 0) return 0;
    precision = precision || 0;
    var c = Math.pow(10, precision);
    return Math.round(this * c) / c;
}
window.parseNumber = function (v) {
    if (v && typeof (v) == "string") return v.toNumber();
    else if (!isNaN(v)) return v;
    else return 0;
}
//选中编辑框内的文本。
//startIndex、length为可选参数，如果不传则默认全部选中。
function selectText(id, startIndex, length) {
    var ctrl = document.getElementById(id);
    startIndex = startIndex || 0;
    length = length || ctrl.value.length;
    if (ctrl.createTextRange) {
        var textRange = ctrl.createTextRange();
        //    ctrl.focus();
        try {
            ctrl.focus();
            textRange.moveEnd('character', length - (ctrl.value.length - startIndex));
            textRange.moveStart('character', startIndex);
            textRange.select();
        } catch (e) {
        }
    }
    else if (ctrl.setSelectionRange) {
        try {
            ctrl.focus();
            setTimeout(function () {
                ctrl.setSelectionRange(startIndex, length);
            }, 100);
        } catch (e) {
        }
    }
}

//深度拷贝
window.deepCopy = function (obj) {
    if (Object.prototype.toString.call(obj) === '[object Array]') {
        var out = [], i = 0, len = obj.length;
        for (; i < len; i++)
            out[i] = arguments.callee(obj[i]);
        return out;
    }
    if (obj && typeof obj === 'object') {
        var out = {}, i;
        for (i in obj)
            out[i] = arguments.callee(obj[i]);
        return out;
    }
    return obj;
}
//Object.prototype.clone = function() {
//    return window.deepCopy(this);
//};
Array.prototype.clone = function () {
    return window.deepCopy(this);
}
window.UrlParser = function (url) {
    /// <summary>
    /// url 解析器
    /// </summary>
    /// <param name="url">指定url，缺省值为window.location.href</param>
    url = url || window.location.href;
    this.params = [];
    this.keys = [];
    this.queryString = "";
    var index = url.indexOf("?");
    this.domain = url.substr(0, index);
    if (index > 0) {
        this.queryString = url.substring(index + 1, url.length);
        var arrArgs = this.queryString.split("&");
        if (arrArgs.length > 0) {
            for (var i = 0; i < arrArgs.length; i++) {
                var arr = arrArgs[i].split("=");
                this.params[arr[0]] = arr[1];
                this.keys[i] = arr[0];
            }
        }
    }
    this.getSearch = function () {
        var p = [];
        for (var i = 0; i < this.keys.length; i++)
            p.push(this.keys[i] + "=" + this.params[this.keys[i]]);
        return p.join("&");
    };
    this.getUrl = function () {
        var q = this.getSearch();
        this.domain + (!!q ? ("?" + q) : "");
    };
};
//委托，用于事件管理
var Delegate = function (cfg) {
    var list = [];
    this.scope = this;
    this.breakOnError = false;
    //init
    if (!!cfg) for (var p in cfg)
        this[p] = cfg[p];
    this.add = function (func) {
        list.push(func);
    }
    this.exec = function () {
        for (var i = 0; i < list.length; i++)
            if (list[i].apply(this.scope, arguments) === false && this.breakOnError === true) break;
    }
}
try {
    if (jQuery);
} catch (e) {
    jQuery = false;
}
if (jQuery) {
    $.trimEx = function (value) {
        if (value && typeof (value) == "string") return value.replace(/(^\s*)|(\s*$)/g, "");
        else return value;
    };
    window.jQueryRequest = function (url, async, params, onsuccess, onfail) {
        $.ajax({
            type: "POST",
            async: async || false,
            dataType: "json",
            url: url,
            data: params,
            success: function (result) {
                if (result.success === true) {
                    if (onsuccess) onsuccess(result);
                }
                else if (onfail) onfail(result);
                //else extAlert("提示", result.message);
            }
        });
    };
} else {
    window.jQueryRequest = false;
}
window.request = function (url, params, onsuccess, onfail) {
    if (window.jQueryRequest) jQueryRequest(url, false, params, onsuccess, onfail);
};
window.asyncRequest = function (url, params, onsuccess, onfail) {
    if (window.jQueryRequest) jQueryRequest(url, true, params, onsuccess, onfail);
};
function activeAutoComplete(control) {
    var customOptions = { text_field: "Name", value_field: "Id", delay: 400 };
    try {
        $.extend(customOptions, eval("(" + $(control).data("autocomplete-options") + ")"));
        if (customOptions.data) {
            if (typeof (customOptions.data) === "string") customOptions.source = (function (val, fn) { request(this.options.data, { keyword: val }, function (result) { fn(result.data); }); });
            else if (typeof (customOptions.data) === "function") customOptions.source = customOptions.data.call(control, customOptions);
            else customOptions.source = customOptions.data;
            control._autocomplete = customOptions;
        }
        $(control).autocomplete(customOptions);
    }
    catch (e) {

    }
}
if (jQuery.validator) {
    jQuery.validator.addMethod("conditional", function (val, element) {
        if (!this.optional(element)) {
            var evalCode = $(element).attr("conditional");
            evalCode.replace(/\{value\}/, val);
            if (evalCode) {
                try {
                    var fn = new Function("self", "val", evalCode);
                    var success = fn.call(element, element, val);
                    if (success === false) return false;
                }
                catch (e) {
                }
            }
            return true;
        }
        return false;
    });
    $(document).ready(function () {
        for (var i = 0; i < document.forms.length; i++) {
            var form = $(document.forms[i]);
            var needValidate = form.data("need-validate") == true;
            if (needValidate) form.submit(function (e) {
                var $this = $(this);
                return e.result = $this.validate({ errorLabelContainer: $this.data("error-label") }).form();
            });
        }
    });
}
function copyToClipboard(txt) {
    if (window.clipboardData) {
        window.clipboardData.clearData();
        window.clipboardData.setData("Text", txt);
    } else if (navigator.userAgent.indexOf("Opera") != -1) {
        window.location = txt;
    } else if (window.netscape) {
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        } catch (e) {

        }
        var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
        if (!clip) return;
        var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
        if (!trans) return;
        trans.addDataFlavor('text/unicode');
        var str = new Object();
        var len = new Object();
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        var copytext = txt;
        str.data = copytext;
        trans.setTransferData("text/unicode", str, copytext.length * 2);
        var clipid = Components.interfaces.nsIClipboard;
        if (!clip) return false;
        clip.setData(trans, null, clipid.kGlobalClipboard);
    }
    else {
        return false;
    }
}